package com.code;


public class PropertyBuilderOfAsc implements PropertyBuilder{

	@Override
	public short[] buildProperty(int code, int len, String value) {
		short []ascByte=new short[len+1];
		char[] chars=value.trim().toCharArray();
		int j=chars.length;
    	for(int i=1;i<ascByte.length;i++){
			if ((i-1)<j){
				ascByte[i]= String.valueOf(chars[i-1]).getBytes()[0];
			}else if ((i-1)==j){
				ascByte[i]=(short)0x24;
			}else{
				ascByte[i]=(short)0x00;
			}	
    	}
    	ascByte[0]=(short)code;
		return ascByte;
	}

	@Override
	public String translateData(byte[] datas, int len, int offset) {
		StringBuffer sb=new StringBuffer();
		for (int i=offset+1;i<len+offset+1;i++){
			if (Integer.parseInt(String.format("%02X", datas[i]),16)==36) break;
			sb.append(new Character((char) datas[i]).toString());
		}
        return sb.toString();
	}

	@Override
	public String encode(String pvalue, int length) {
		StringBuffer sb=new StringBuffer();
		if (pvalue==null){
			sb.append("24");
			for (int i=1;i<length;i++){
				sb.append("00");
			}
		}else{
			char[] chars=pvalue.trim().toCharArray();
			int j=chars.length;
			if (j==0) return "";
			
			for (int i=0;i<length;i++){
				if (i<j){
					//byte[] byteValue=String.valueOf(chars[i]).getBytes();
					sb.append(String.format("%02X", String.valueOf(chars[i]).getBytes()[0]));
				}else if (i==j){
					sb.append("24");
				}else{
					sb.append("00");
				}
			}
		}
		return sb.toString();
	}

	@Override
	public String decode(String pdata, int length) {
		byte[] data=ByteUtil.hexStringToBytes(pdata);
		StringBuffer sb=new StringBuffer();
		for (int i=0;i<data.length;i++){
			if (Integer.parseInt(String.format("%02X", data[i]),16)==0x24) break;
			if (Integer.parseInt(String.format("%02X", data[i]),16)==0x00) break;
			sb.append(new Character((char) data[i]).toString());
		}
		return sb.toString();
	}

	@Override
	public String parseValue(String pvalue) {
		return pvalue;
	}



}
